#include "liblwm2m.h"
#include "lwm2mclient.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PRV_TLV_BUFFER_SIZE 64

typedef struct _prv_instance_
{
    struct _prv_instance_ *next; // matches lwm2m_list_t::next
    uint16_t instanceId;         // matches lwm2m_list_t::id
    uint8_t test;
} prv_instance_t;

static uint8_t
prv_read (lwm2m_context_t *contextP, uint16_t instanceId, int *numDataP, lwm2m_data_t **dataArrayP,
          lwm2m_object_t *objectP)
{
    prv_instance_t *targetP;
    uint8_t mybuffer[1];
    (void)contextP;

    targetP = (prv_instance_t *)lwm2m_list_find (objectP->instanceList, instanceId);
    // *numDataP默认为1，因为服务端默认发送读取URI为/19/0/0，指定了实例ID，故默认值为1
    // 若服务端发送URI为/19，没有指定实例ID，则值为对象19下的所有实例数量
    if (*numDataP == 1)
        {
            switch ((*dataArrayP)[0].id)
                {
                // 指定资源ID处理
                // 发送URI为/19/0/0
                case 0:

                    mybuffer[0] = targetP->test;
                    lwm2m_data_encode_opaque (mybuffer, sizeof (mybuffer), *dataArrayP);
                    break;
                // 发送URI为19/0/1
                case 1:
                    // 你的数据处理
                    break;
                default:
                    return COAP_404_NOT_FOUND;
                }
        }
    return COAP_205_CONTENT;
}

lwm2m_object_t *
get_test_object (int value)
{
    lwm2m_object_t *testObj;

    testObj = (lwm2m_object_t *)lwm2m_malloc (sizeof (lwm2m_object_t));

    if (NULL != testObj)
        {
            prv_instance_t *targetP;
            memset (testObj, 0, sizeof (lwm2m_object_t));
            testObj->objID = 19;
            targetP = (prv_instance_t *)lwm2m_malloc (sizeof (prv_instance_t));
            memset (targetP, 0, sizeof (prv_instance_t));
            targetP->instanceId = 0;
            targetP->test = value;
            testObj->instanceList = LWM2M_LIST_ADD (testObj->instanceList, targetP);
            testObj->readFunc = prv_read;
        }
    return testObj;
}

void
free_test_object (lwm2m_object_t *object)
{
    prv_instance_t *targetP = (prv_instance_t *)object->instanceList;
    while (targetP != NULL)
        {
            prv_instance_t *next = targetP->next;
            targetP = next;
        }
    LWM2M_LIST_FREE (object->instanceList);
    if (object->userData != NULL)
        {
            lwm2m_free (object->userData);
            object->userData = NULL;
        }
    lwm2m_free (object);
}
